package com.sunwoda.demo.config;

import com.sunwoda.demo.realm.MyRealm;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


/**
 * Description:
 *
 * @author shiguorang
 * @date 2021-03-17 16:41:31
 */
@Configuration
public class ShiroConfig {

    /**
     * @return
     * @Author shiguorang
     * @Description //创建shiro拦截器
     * @Date 16:41:38 2021-03-17
     * @Param
     **/
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
//        定义拦截策略，公共放行的放前面
        Map<String, String> map = new HashMap<>();
        map.put("/login.jsp", "anon");
        map.put("/user/login", "anon");
        map.put("/registered.jsp", "anon");
        map.put("/user/registered", "anon");
        map.put("/**", "authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        return shiroFilterFactoryBean;
    }

    /**
     * @Author shiguorang
     * @Description //创建安全管理器
     * @Date 16:43:18 2021-03-17
     * @Param
     * @return
     **/
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("getRealm") Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }

    /**
     * @Author shiguorang
     * @Description //创建realm
     * @Date 16:44:15 2021-03-17
     * @Param
     * @return
     **/
    @Bean
    public Realm getRealm(){
        MyRealm myRealm = new MyRealm();
//        修改默认凭证比较器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
//        设置加密算法名称
        credentialsMatcher.setHashAlgorithmName("MD5");
//        设置散列次数
        credentialsMatcher.setHashIterations(1024);
        myRealm.setCredentialsMatcher(credentialsMatcher);
        return myRealm;
    }
}
